$(function () {
	var timer = null;

	// 添加表情
	for (let i = 0; i <= 71; i++) {
		$('.biaoqing-photo ul').append('<li><img class="emoji-picker-image" data-id="'+ i + '" src="/static/images/face/' + i + '.gif" alt="" /></li>');
	}

	// 打开关闭聊天框
	$(".chatBtn").click(function () {
		updateChatList();
        $(".chatBox").toggle(10);
    })
    $(".chat-close").click(function () {
        $(".chatBox").toggle(10);
    })

    // 添加用户到聊天列表
    $("#chatAdd").click(function () {
    	$.post("/index/chat/getAllUsers", { }, 
    	function(result) {
    		if (result.status == "success") {
    			$('.dropdown-item').off('click');
				var div1 = '<a class="dropdown-item" href="javascript:void(0);" friend-id="';
				var div2 = '">';
				var div3 = '</a>';
				for (var user of result.data) {
					$('#chatAllList').append(div1 + user.id + div2 + user.fullname);
				}
				$('.dropdown-item').click(function() {
					var friend_id = $(this).attr('friend-id');
			    	$.post("/index/chat/addChatList", {
			    		'friend_id': friend_id
			    	}, function(result) {
			    		if (result.status == 'success') {
			    			updateChatList();
			    		}
			    	}, "json");
			    });
			}
    	}, "json");
    });
    
    // 从聊天列表删除
    $('body').on('click', '.delete_chat', function() {
		var friend_id = $(this).attr('class').substr(12);
		$.post("/index/chat/deleteChatList", {
			'friend_id': friend_id
		}, function(result) {
			if (result.status == 'success') {
				$('.popover').popover('hide');
				updateChatList();
			}
		}, "json");
	});

	$('#chatList').on('dblclick', '.chat-list-people', function() {
		clearTimeout(timer);
		$(this).popover('toggle');
	});

    // 进入聊天页面
	$('#chatList').on('click', '.chat-list-people', function() {
		clearTimeout(timer);
		var avator_val = $(this).find('img').attr('src');
		var fullname_val = $(this).find('p').html();
		var friend_id = $(this).attr('data-id');

        timer = setTimeout(function() {
            $('.chatBox-head-one').toggle();
	        $('.chatBox-head-two').toggle();
	        $('.chatAddBtn').toggle();
	        $('.chatBox-list').fadeToggle();
	        $('.chatBox-kuang').fadeToggle();
	        $('#head_avator').attr('src', avator_val);
	        $('#head_fullname').html(fullname_val);
	        getContent(friend_id);
	        
        }, 300);
	});

	// 返回
    $(".chat-return").click(function () {
        $(".chatBox-head-one").toggle(1);
        $(".chatBox-head-two").toggle(1);
        $('.chatAddBtn').toggle(1);
        $(".chatBox-list").fadeToggle(1);
        $(".chatBox-kuang").fadeToggle(1);
    });

    // 发送信息
    $("#chat-send").click(function () {
    	var text_content = $(".div-textarea").html().replace(/[\n\r]/g, '<br>');
    	var friend_id = $('.chatBox-kuang').attr('data-id');
    	if (text_content != "") {
    		$.post("/index/chat/addChatContent", {
    			'friend_id': friend_id,
    			'content': text_content
    		}, function(result) {
    			if (result.status == 'success') {
    				var div1 = '<div class="clearfloat"><div class="author-name">';
		        	var div_time1 = '<small class="chat-date">';
		        	var div_time2 = '</small>';
		        	var div2 = '</div><div class="right"><div class="chat-message">';
		        	var div3 = '</div></div></div>';
    				$(".chat-content").append(div1 + div2 + text_content + div3);
    				$(".div-textarea").html("");
		            $(".chat-content").scrollTop($(".chat-content")[0].scrollHeight);
    			}
    		}, "json");
    	}
    });

    // 选择表情
    $(document).click(function () {
        $('.biaoqing-photo').hide();
        $('.popover').popover('hide');
    });
    $("#chat-biaoqing").click(function (event) {
        event.stopPropagation();
        $(".biaoqing-photo").toggle();
    });

    $(".emoji-picker-image").each(function () {
    	$(this).click(function() {
    		var emoji_id = $(this).attr('data-id');
    		var ocontent = $('.div-textarea').html();
    		var emoji_div = '<img class="emoji-picker-image" src="/static/images/face/' + emoji_id + '.gif" alt="" />';
    		$('.div-textarea').html(ocontent + emoji_div);
    	});
    });
});

function getChatMessageCount() {
	$.get("/index/chat/getAllNum", 
	function(result) {
		if (result.status == 'success') {
			if (result.data != 0) {
				$('#chat_num').text(result.data);
				$('#chat_num').show();
			}
			else {
				$('#chat_num').hide();
			}
		}
		if (result.status == 'error') {
			$('#chat_num').hide();
			$('#chat_num').text(0);
		}
	}, "json");
};

var secondInterval;
function secondAlert(){
	if(secondInterval) {
		clearInterval(secondInterval);
	}
	getChatMessageCount();
    secondInterval = setInterval('secondAlert()', 1000 * 60 * 2);
}
secondAlert();

function updateChatList() {
	//获取聊天列表
    $.post("/index/chat/getChatList", { }, 
    function(result) {
    	var div1 = '<div class="chat-list-people" data-id="';
    	var div2 = '" data-container="body" data-toggle="popover" data-trigger="focus" data-placement="top" data-content="<div class=\'delete_chat ';
    	var div3 = '\'>删除</div>"><div><img src="/static/images/avator';
    	var div4 = '"/></div><div class="chat-name"><p>';
    	var div5 = '</p></div><div class="message-num">';
    	var div6 = '</div></div>';
    	if (result.status == 'success') {
    		$('#chatList').empty();
    		for (var data of result.data) {
				var div = div1 + data.id + div2 + data.id + div3 + data.avator_path + div4 + data.fullname + div5 + data.unread + div6;
    			$('#chatList').append(div);
    		}
    		$('[data-toggle="popover"]').popover({
				html: true
			});    			
    	}
    }, "json");
}

function getContent(friend_id) {
	// 获取聊天内容
	$.post("/index/chat/getChatContent", {
    	'friend_id': friend_id
    }, function(result) {
    	var div1 = '<div class="clearfloat"><div class="author-name">';
    	var div_time1 = '<small class="chat-date">';
    	var div_time2 = '</small>';
    	var div2 = '</div><div class="';
    	var div3 = '"><div class="chat-message">';
    	var div4 = '</div></div></div>';
    	if (result.status == 'success') {
    		$('.chat-content').empty();
    		for (var i in result.data) {
    			var data = result.data[i];

    			var content = '';
    			if (i >= 1) {
    				var datal = result.data[i-1];
    				if (dateDiff(data.create_time, datal.create_time) > 300) {
    					content += div1 + data.create_time;
    				}
    				else {
    					content += div1;
    				}
    			}
    			else {
    				content += div1 + data.create_time;
    			}

    			if (data.uid == data.sender) {
    				content += div2 + 'right' + div3 + data.content + div4;
    			}
    			else {
    				content += div2 + 'left' + div3 + data.content + div4;
    			}
    			$('.chat-content').append(content);
    		}
    		$('.chatBox-kuang').attr('data-id', friend_id);
    		$(".chat-content").scrollTop($(".chat-content")[0].scrollHeight);
    	}
    }, "json");
}

function updateContent(friend_id) {
	$.post("/index/chat/getChatContent", {
    	'friend_id': friend_id
    }, function(result) {
    	var div1 = '<div class="clearfloat"><div class="author-name">';
    	var div_time1 = '<small class="chat-date">';
    	var div_time2 = '</small>';
    	var div2 = '</div><div class="';
    	var div3 = '"><div class="chat-message">';
    	var div4 = '</div></div></div>';
    	if (result.status == 'success') {
    		$('.chat-content').empty();
    		for (var i in result.data) {
    			var data = result.data[i];

    			var content = '';
    			if (i >= 1) {
    				var datal = result.data[i-1];
    				if (dateDiff(data.create_time, datal.create_time) > 300) {
    					content += div1 + data.create_time;
    				}
    				else {
    					content += div1;
    				}
    			}
    			else {
    				content += div1 + data.create_time;
    			}

    			if (data.uid == data.sender) {
    				content += div2 + 'right' + div3 + data.content + div4;
    			}
    			else {
    				content += div2 + 'left' + div3 + data.content + div4;
    			}
    			$('.chat-content').append(content);
    		}
    		$('.chatBox-kuang').attr('data-id', friend_id);	
    	}
    }, "json");
}

var thirdInterval;
function thirdAlert(){
	if(thirdInterval) {
		clearInterval(thirdInterval);
	}
	if ($('.chatBox-kuang').is(':visible')) {
		var friend_id = $('.chatBox-kuang').attr('data-id');
		updateContent(friend_id);
		getChatMessageCount();
	}
	else {
		if ($('#chatList').is(':visible')) {
			updateChatList();
			getChatMessageCount();
        }
        else {
        	getChatMessageCount();
        }
	}
    thirdInterval = setInterval('thirdAlert()', 1000 * 1 * 1);
}
thirdAlert();

// 时间比较方法
function dateDiff(date1, date2){ 
    var type1 = typeof date1, type2 = typeof date2; 
    if(type1 == 'string') {
    	date1 = stringToTime(date1); 
    }
    else if(date1.getTime)  {
    	date1 = date1.getTime(); 
    }
    
    if(type2 == 'string') {
    	date2 = stringToTime(date2);
    }
    else if(date2.getTime) {
    	date2 = date2.getTime(); 
    } 
    return (date1 - date2) / 1000;
}

function stringToTime(string){ 
    var f = string.split(' ', 2); 
    var d = (f[0] ? f[0] : '').split('-', 3); 
    var t = (f[1] ? f[1] : '').split(':', 3); 
    return (new Date( 
    parseInt(d[0], 10) || null, 
    (parseInt(d[1], 10) || 1)-1, 
    parseInt(d[2], 10) || null, 
    parseInt(t[0], 10) || null, 
    parseInt(t[1], 10) || null, 
    parseInt(t[2], 10) || null 
    )).getTime();
}

